// pages/recommendSong/recommendSong.js
import request from '../../../untils/request'
import PubSub from 'pubsub-js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    day: '', //天
    month: '', //月
    recommentList: [],
    index: '', //当前播放音乐下标

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let userInfo = wx.getStorageSync('userInfo')
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        success: () => {
          wx.reLaunch({
            url: '/pages/login/login',
          })
        }
      })

    }

    this.setData({
      day: new Date().getDate(),
      month: new Date().getMonth() + 1
    })
    this.getRecommentList()
    //订阅来自songDetail页面发布的信息
    PubSub.subscribe('switchType', (msg, Type) => {
      let {
        recommentList,
        index
      } = this.data
      console.log(msg, Type)
      if (Type == 'pre') {
        //上一首
        index == 0 && index == recommentList.length
        index -= 1
      } else {
        (index == recommentList.length - 1) && (index == -1)
        index += 1

      }

      this.setData({
        index
      })

      let musicId = recommentList[index].id

      //将音乐Id回传给songDetail页面

      PubSub.publish('musicId', musicId)
    })


  },
  async getRecommentList() {
    let recommentListData = await request('/recommend/songs')
    this.setData({
      recommentList: recommentListData.recommend
    })
  },

  toSongDetail(event) {
    let {
      song,
      index
    } = event.currentTarget.dataset
    this.setData({
      index
    })
    wx.navigateTo({
      url: '/songPacKage/pages/songDetail/songDetail?musicId=' + song.id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})